package bookstudytest.proxy.intercepter;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.Intercepter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: Lee
 * @Date: 2019/3/8 0008 14:55
 * @Description:
 */
public class IntercepterJdkDemo implements InvocationHandler {
    private Object target;
    private String interceptorClassName = null;

    public IntercepterJdkDemo(Object target, String interceptorClassName) {
        this.target = target;
        this.interceptorClassName = interceptorClassName;
    }

    public static Object bind(Object target, String interceptorClassName) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), new IntercepterJdkDemo(target, interceptorClassName));
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (this.interceptorClassName == null) {
            // 无拦截器
            return method.invoke(this.target, args);
        }
        Class<?> aClass = Class.forName(this.interceptorClassName);
        IntercepterByJdk intercepterByJdk = (IntercepterByJdk) aClass.newInstance();
        if (!intercepterByJdk.before(proxy, this.target, method, args)) {
            return null;
        }
        Object result = intercepterByJdk.around(proxy, this.target, method, args);

        intercepterByJdk.after(proxy, this.target, method, args);
        return result;
    }
}
